import React from 'react';
import { useDeviceContext } from './DeviceContext';

interface DeviceListProps {
  onTransfer?: (deviceId: string) => void;
  onRun?: (deviceId: string) => void;
}

const DeviceList: React.FC<DeviceListProps> = ({ onTransfer, onRun }) => {
  const { devices, loading, refresh } = useDeviceContext();
  const [wsPort, setWsPort] = React.useState<number | null>(null);

  React.useEffect(() => {
    refresh();
    const interval = setInterval(refresh, 5000);
    return () => clearInterval(interval);
  }, [refresh]);

  // 监听WebSocket服务器启动
  React.useEffect(() => {
    if (!window.ipcApi) return;

    const removeWsListener = window.ipcApi.onWebSocketServerStarted((event) => {
      setWsPort(event.port);
    });

    return () => {
      removeWsListener();
    };
  }, []);

  return (
    <div className="device-list">
      <div className="device-list-header">
        <h3>设备列表</h3>
        <button onClick={refresh} disabled={loading}>
          {loading ? '扫描中...' : '刷新'}
        </button>
      </div>
      
      {wsPort && (
        <div className="ws-info">
          AutoJS连接地址: ws://localhost:{wsPort}
        </div>
      )}

      {devices.length === 0 ? (
        <div className="no-devices">
          {loading ? '正在扫描设备...' : '未检测到设备'}
        </div>
      ) : (
        <div className="device-items">
          {devices.map(device => (
            <div key={device.id} className="device-item">
              <div className="device-info">
                <div className="device-model">{device.model}</div>
                <div className="device-id">{device.id}</div>
                <div className="connection-type">
                  {device.isWebSocket ? '通过WebSocket连接' : '通过ADB连接'}
                </div>
              </div>
              <div className="device-actions">
                <button onClick={() => onTransfer?.(device.id)}>
                  传输文件
                </button>
                {device.isWebSocket && (
                  <button 
                    onClick={() => onRun?.(device.id)}
                    className="run-button"
                  >
                    运行
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default DeviceList; 